package com.hkd.forum.controller;

import com.hkd.forum.common.AppResult;
import com.hkd.forum.common.ResultCode;
import com.hkd.forum.exception.ApplicationException;
import com.hkd.forum.model.Board;
import com.hkd.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "板块接口")
@RestController
@RequestMapping("/board")
public class BoardController {
    //从配置项中取值 默认为 :9
    @Value("${bit-forum.index.board-num:9}")
    private Integer indexBoardValue;
    @Autowired
    private IBoardService boardService;

    /**
     * 查询首页板块列表
     * @return
     */

    @ApiOperation("获取首页列表板块")
    @GetMapping("/topList")
    public AppResult<List<Board>> topList () {

        log.info("首页板块数为"+indexBoardValue);
        List<Board> boards = boardService.selectByNum(indexBoardValue);

        if( boards == null){
            //为了正常返回Json
            boards = new ArrayList<>();
        }

        //返回结果
        return AppResult.success(boards);
    }
    @ApiOperation("获取板块信息")
    @GetMapping("/getById")
    public AppResult<Board> getById(@ApiParam("板块id") @RequestParam("id") @NonNull Long id) {
        //调用service
        Board board = boardService.selectById(id);
        //对查询结果进行校验
        if(board == null || board.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString(),"板块id:"+id+"查询结果为空或已被删除");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //返回结果
        return AppResult.success(board);
    }
}
